package mm.http;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import mm.util.I18NMap;
import mm.util.LOG;

public class SystemListener implements ServletContextListener {
	
	private static ApplicationContext context;
	private static boolean debugging=true;
	private String contextFilePath;
	
	/**
	 * For testing
	 */
	public SystemListener(String _contextFilePath){
		if(_contextFilePath!=null)
			contextFilePath=_contextFilePath;
		else
			contextFilePath="/spring_test.xml";
		contextInitialized(null);
	}
	
	/**
	 * For real world
	 */
	public SystemListener(){
		;
	}

	public void contextDestroyed(ServletContextEvent evt) {
		;
	}

	public void contextInitialized(ServletContextEvent evt) {
		if(contextFilePath==null&&evt!=null)
			contextFilePath=evt.getServletContext().getInitParameter("springXML");
		if(evt!=null){
			debugging="true".equals(evt.getServletContext().getInitParameter("debug"));
			if(debugging)
				LOG.info("Using debug mode now.");
		}
		if(contextFilePath==null||contextFilePath.trim().length()<1)
			contextFilePath="/spring.xml";
		try{
			context=new ClassPathXmlApplicationContext(contextFilePath);
		}catch(Throwable t){
			throw new RuntimeException("", t);
		}
		I18NMap.initInstances();
	}

	/**
	 * @return the context
	 */
	public static ApplicationContext getContext() {
		return context;
	}

	public static boolean isDebugging() {
		return debugging;
	}

}
